package com.linln.admin.cmedic.controller;

import com.linln.admin.cmedic.domain.CmedicineInfo;
import com.linln.admin.cmedic.service.CmedicineInfoService;
import com.linln.admin.cmedic.validator.CmedicineInfoValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.vo.ResultVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author wh
 * @date 2024/03/26
 */
@Controller
@RequestMapping("/cmedic/")
public class CmedicineInfoController {

    @Autowired
    private CmedicineInfoService cmedicineInfoService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("cmedic::index")
    public String index(Model model, CmedicineInfo cmedicineInfo) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("title", match -> match.contains())
                .withMatcher("intro", match -> match.contains())
                .withMatcher("plantGenus", match -> match.contains())
                .withMatcher("plantFrature", match -> match.contains())
                .withMatcher("plantCropArea", match -> match.contains())
                .withMatcher("plantRealEstate", match -> match.contains())
                .withMatcher("plantGrowthEnvironment", match -> match.contains())
                .withMatcher("plantGrowthHabits", match -> match.contains())
                .withMatcher("plantsireMethods", match -> match.contains())
                .withMatcher("plantTrainTechniques", match -> match.contains())
                .withMatcher("plantPestControl", match -> match.contains())
                .withMatcher("plantMajorVariant", match -> match.contains())
                .withMatcher("chineseName", match -> match.contains())
                .withMatcher("chinesePinyin", match -> match.contains())
                .withMatcher("latinName", match -> match.contains())
                .withMatcher("alisaName", match -> match.contains())
                .withMatcher("thumbnail", match -> match.contains())
                .withMatcher("storageMethod", match -> match.contains())
                .withMatcher("realEstate", match -> match.contains())
                .withMatcher("drugSite", match -> match.contains())
                .withMatcher("remark", match -> match.contains())
                .withMatcher("func", match -> match.contains())
                .withMatcher("mainAttend", match -> match.contains());

        // 获取数据列表
        Example<CmedicineInfo> example = Example.of(cmedicineInfo, matcher);
        Page<CmedicineInfo> list = cmedicineInfoService.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/cmedic//index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("cmedic::add")
    public String toAdd() {
        return "/cmedic//add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("cmedic::edit")
    public String toEdit(@PathVariable("id") CmedicineInfo cmedicineInfo, Model model) {
        model.addAttribute("cmedicineInfo", cmedicineInfo);
        return "/cmedic//add";
    }

    /**
     * 保存添加/修改的数据
     *
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"cmedic::add", "cmedic::edit"})
    @ResponseBody
    public ResultVo save(@Validated CmedicineInfoValid valid, CmedicineInfo cmedicineInfo) {
        // 复制保留无需修改的数据
        if (cmedicineInfo.getId() != null) {
            CmedicineInfo beCmedicineInfo = cmedicineInfoService.getById(cmedicineInfo.getId());
            EntityBeanUtil.copyProperties(beCmedicineInfo, cmedicineInfo);
        }

        // 保存数据
        cmedicineInfoService.save(cmedicineInfo);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 爬取数据
     */
    @GetMapping("/crawl")
    @RequiresPermissions({"cmedic::add", "cmedic::edit"})
    @ResponseBody
    public ResultVo crawl(String keyword) {
        // 保存数据
        cmedicineInfoService.crawlBySearch(keyword, 1);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 爬取数据
     */
    @GetMapping("/crawlByThread")
    @RequiresPermissions({"cmedic::add", "cmedic::edit"})
    @ResponseBody
    public ResultVo crawlByThread(@RequestParam(defaultValue = "1100000") Integer no) throws InterruptedException {
        if (no < 1100000) {
            no = 1100000;
        }
        // 保存数据
        cmedicineInfoService.crawlByThread(no);
        return ResultVoUtil.SAVE_SUCCESS;
    }


    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("cmedic::detail")
    public String toDetail(@PathVariable("id") CmedicineInfo cmedicineInfo, Model model) {
        model.addAttribute("cmedicineInfo", cmedicineInfo);
        return "/cmedic//detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("cmedic::status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Integer> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (cmedicineInfoService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}